import config from './config.js'
import store from '@/store/index.js'
import { validURL } from '@/utils/validate'
import Axios from 'axios'

export default {
  ajax: function(p) {
    const obj = {
      cbSuccess: function() {},
      cbError: function() {},
      method: 'post',
      path: '',
      data: {},
      header: {},
      showLoading: function() {},
      hideLoading: function() {},
      cbFinally: function() {}
    }
    store.dispatch('getAuth')
    obj.header.Authorization = 'Bearer ' + store.getters.auth('jwt')

    Object.assign(obj, p)
    obj.showLoading()

    const that = this

    const AxiosURL = validURL(obj.path) ? obj.path : config.apiURI + obj.path

    Axios({
      url: AxiosURL,
      method: obj.method,
      data: obj.data,
      headers: obj.header
    }).then(function(res) {
      const data = res.data
      if (data.status === 200) {
        obj.cbSuccess(data)
      } else if (data.status === 400) {
        if (data.msg !== 'auth_timeout') {
          const authErrors = ['auth_empty', 'auth_error', 'auth_refresh_error']
          if (authErrors.indexOf(data.msg) >= 0) {
            store.dispatch('loginOut')
            store.dispatch('loginNeed')
          }
          obj.cbError(data)
        } else {
          that.refreshJwt(p)
        }
      } else {
        obj.cbError({ msg: 'unknown_error' })
      }
      obj.hideLoading()
      obj.cbFinally()
    }).catch(function(error) {
      obj.hideLoading()
      obj.cbError({ msg: 'net_error' })
      obj.cbFinally()
      console.log(error)
    })
  },
  refreshJwt: function(p) {
    const uinfo = store.getters.auth('jwtRef')
    if (uinfo === null) {
      store.dispatch('loginOut')
      store.dispatch('loginNeed')
      return false
    }
    const that = this
    that.ajax({
      path: config.refreshJwt,
      method: 'get',
      header: {
        'Authorization': 'Bearer ' + uinfo
      },
      cbSuccess: function(res) {
        store.dispatch('updateAuth', { jwt: res.memo.jwt, jwtRef: res.memo.jwt_refresh })
        that.ajax(p)
      },
      cbError: function() {
        store.dispatch('loginOut')
        store.dispatch('loginNeed')
      }
    })
  },
  verify: {
    check: function(vdata) {
      for (const d in vdata) {
        const v = vdata[d]
        for (const r in v.rules) {
          const rdata = v.rules[r]
          if (this.rules['_' + r](v.val, rdata.args) === false) {
            return rdata.msg
          }
        }
      }
      return true
    },
    rules: {
      _required: function(val) {
        if (val !== '') {
          return true
        }
        return false
      },
      _email: function(val) {
        const p = /^[a-zA-Z0-9._%+-]+@(?!.*\.\..*)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/
        return p.test(val)
      },
      _mobile: function(val) {
        const p = /^(13|14|15|16|17|18|19)\d{9}$/
        return p.test(val)
      },
      _alphanumeric: function(val) {
        const p = /^\w+$/
        return p.test(val)
      },
      _digits: function(val) {
        const p = /^[-,+]?\d+$/
        return p.test(val)
      },
      _number: function(val) {
        const p = /^[-,+]?\d+(\.\d+)?$/
        return p.test(val)
      },
      _equalTo: function(val, args) {
        if (val === args[0]) {
          return true
        }
        return false
      },
      _rangeLength: function(val, args) {
        if (val.length <= args[1] && val.length >= args[0]) {
          return true
        }
        return false
      },
      _equalLength: function(val, args) {
        if (val.length === args[0]) {
          return true
        }
        return false
      },
      _maxLength: function(val, args) {
        if (val.length <= args[0]) {
          return true
        }
        return false
      },
      _minLength: function(val, args) {
        if (val.length >= args[0]) {
          return true
        }
        return false
      },
      _date: function(val) {
        const p = /^(\d{4})-(0\d{1}|1[0-2])-(0\d{1}|[12]\d{1}|3[01])$/
        return p.test(val)
      }
    },
    addRule: function(name, fn) {
      this.rules['_' + name] = fn
    }
  },
  formatDate: function(odate, format) {
    const myDate = new Date(odate)
    const m = myDate.getMonth() + 1
    const d = myDate.getDate()
    const h = myDate.getHours()
    const i = myDate.getMinutes()
    const s = myDate.getSeconds()
    format = format.replace('yyyy', myDate.getFullYear())
    format = format.replace('mm', m < 10 ? ('0' + m) : m)
    format = format.replace('dd', d < 10 ? ('0' + d) : d)
    format = format.replace('hh', h < 10 ? ('0' + h) : h)
    format = format.replace('ii', i < 10 ? ('0' + i) : i)
    format = format.replace('ss', s < 10 ? ('0' + s) : s)
    return format
  }
}
